<?php
/**
 * Created by PhpStorm.
 * User: zyh
 * Date: 2018/5/9
 * Time: 上午10:00
 */

namespace app\index\controller;
use app\admin\model\Rewards;
use app\admin\model\System;
use app\admin\model\User;
use app\index\command\Events;
use GatewayClient\Gateway;
use think\Cache;
use think\Controller;
use think\Session;

class Auth extends Controller
{
    public function login()
    {
        $ismobile = ismobile();
        if ($ismobile){
            return view('auth/mobilelogin');
        }else{
            return view();
        }
    }

    public function logindo()
    {
        $status = [];
        $system = System::getSystem();
        if ($system['status'] == 0 && input('post.username')!='k01'){
            return ['status'=>0,'error'=>'系统维护中,,,'];
        }
        if ($arr = input('post.')){
            if(!captcha_check(input('post.verify'))){
                $status = ['status'=>0,'error'=>'验证码错误!'];
            }else{
                $user = new User();
                if ($u = $user->login($arr)){
                    $status = ['status'=>1];

                }else{
                    $status = ['status'=>0,'error'=>'用户名或密码错误'];
                }
            }
        }
        return $status;
    }

    public function logout()
    {
        Session::set('login',false);
        $this->redirect('auth/login');
    }

    /**
     * @param $clientid
     * @throws \Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     */
    public function bind($clientid)
    {
        //出现空session
        if (!Session::get("user")) return;  //这个参数在cgi中取不出
        $id = Session::get("user")['id'];
        //绑定WEBSOCKET的CLIENTID到用户ID
        Gateway::bindUid($clientid,$id);
        Gateway::joinGroup($clientid,"user");

        Cache::set($clientid . '_login',true) ;//标记在线  预留

        $data['type'] = "user";
        $data['data'] = Session::get('user');
        $data['data']['score'] = User::get($id)['score'];
        $rewards = new Rewards();
        $data['his'] = $rewards->userGameReward($id);
        Events::sendToClient($clientid,json_encode($data));


//        $user = User::get($id);
//        $chat['type'] = 'chat';
//        $chat['data'] = '欢迎【'.$user['username']."】回来。";
//        $chat['from'] = '系统';
//        Events::sendToAll(json_encode($chat));


//        $chat['type'] = 'chat';
//        $chat['data'] = $user['name'].',欢迎回来。健康游戏,祝您节日快乐';
//        $chat['from'] = '系统';
//        Events::sendToClient($clientid,json_encode($chat));
    }

    public function editPassword()
    {
        $password = input("post.password");
        $id = Session::get("user")['id'];
        $user = User::get($id);
        $user->save(['password'=>md5($password)]);
        return json(['status'=>1,'error'=>"修改成功"]);
    }
}